package com.example.imagetest;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class VideoActivity extends AppCompatActivity implements View.OnClickListener {

    private Button button;
    private ImageView control;
    private VideoView videoView;
    private SeekBar seekBar;
    private LinearLayout linearLayout;
    private Handler handler = new Handler();
    public static final String TAG = "VideoActivity";
    private Runnable updateSeekBar;
    private float videoAspectRatio = 1.0f;
    private String url = "https://www.w3schools.com/html/mov_bbb.mp4";
    private float aspectRatio = 1.0f;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        Log.e(TAG, "OnCreate ...");
        button = findViewById(R.id.button);
        control = findViewById(R.id.pause);
        seekBar = findViewById(R.id.seekbar);
        videoView = findViewById(R.id.video);
        linearLayout = findViewById(R.id.linearLayout);

        // 设置VideoView的宽度为屏幕一半
        ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels/2;
        videoView.setLayoutParams(layoutParams);

        // 动态设置 SeekBar 的宽度为屏幕的三分之一
        seekBar.post(() -> {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) seekBar.getLayoutParams();
            params.width = getResources().getDisplayMetrics().widthPixels / 3;
            seekBar.setLayoutParams(params);
        });

        // 当视频准备好时更新 SeekBar 的最大值
        videoView.setOnPreparedListener(mp -> {
            Log.e(TAG, "更新 SeekBar 的最大值");
            seekBar.setMax(videoView.getDuration());


            // 获取视频宽高比
            mp.setOnVideoSizeChangedListener((mp1, width, height) -> {
                Log.e(TAG, "width, height...");
                videoAspectRatio = (float) width / height;
                adjustVideoSize();
            });

            // 定期更新 SeekBar 的进度
            updateSeekBar = new Runnable() {
                @Override
                public void run() {
                    Log.e(TAG, "定期更新 SeekBar 的进度");
                    seekBar.setProgress(videoView.getCurrentPosition());
                    handler.postDelayed(this, 1000);
                }
            };
            handler.post(updateSeekBar);
        });

        // 监听 SeekBar 的拖动事件以实现快进和快退
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    videoView.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 用户开始拖动 SeekBar 时暂停视频
                videoView.pause();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 用户停止拖动 SeekBar 时继续播放视频
                videoView.start();
            }
        });

        // 给两个按钮绑定单击事件
        button.setOnClickListener(this);
        control.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.button) {

            int videoId = 1;
            downLoadVideos(url, videoId);
        } else if (view.getId() == R.id.pause) {
            // 为控制视频按钮设置单击逻辑
            if (videoView.isPlaying()) {
                // 将视频播放状态该为暂停，同时修改图片
                control.setImageResource(R.drawable.show);
                videoView.pause();
            } else {
                control.setImageResource(R.drawable.pause);
                videoView.start();
            }
        }
    }

    public void downLoadVideos(String url, int videoId) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                Log.e(TAG, String.format("DownLoad Failed %s", videoId));
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (!response.isSuccessful()) {
                    Log.e(TAG, String.format("DownLoad Failed %s", response));
                    return;
                } else {
                    File videoFile = new File(getExternalFilesDir(null), "download_video.mp4");
                    InputStream inputStream = response.body().byteStream();
                    OutputStream outputStream = new FileOutputStream(videoFile);
                    try {
                        byte[] buffer = new byte[2048];
                        int byteRead;
                        while ((byteRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, byteRead);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e(TAG, "保存图片失败: " + e.getMessage());
                    } finally {
                        if (inputStream != null) inputStream.close();
                        if (outputStream != null) outputStream.close();
                    }

                    runOnUiThread(() -> {
                        videoView.setVideoURI(Uri.fromFile(videoFile));

                        Log.e(TAG, String.format("uri: %s", Uri.fromFile(videoFile)));
                        videoView.start();
                        Log.e(TAG, String.format("Video Download ans set: %s", url));
                    });
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(updateSeekBar);
    }

    private void adjustVideoSize() {
        // 获取屏幕宽度的一半
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int screenWidthHalf = displayMetrics.widthPixels / 2;

        // 根据视频的宽高比计算视频的高度
        int videoHeight = (int) (screenWidthHalf / videoAspectRatio);

        // 设置 VideoView 的宽高
        ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
        layoutParams.width = screenWidthHalf;
        layoutParams.height = videoHeight;
        videoView.setLayoutParams(layoutParams);

    }

}